package com.minimoment.model.action;

import com.minimoment.base.BaseAction;
import com.minimoment.model.domain.User;
import com.minimoment.util.common.CommomUtils;
import com.minimoment.util.javamail.JavaMailActive;
import com.opensymphony.xwork2.ActionContext;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.validation.SkipValidation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.apache.commons.codec.digest.DigestUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by etund on 2014/10/30.
 */
@Controller
@Scope("prototype")
@SuppressWarnings("all")
public class UserAction extends BaseAction<User>{
//    private String repassword;
    private String lmessage;
    private String emessage;
    private String autoLogin;
    private String securityCode;
    private String register;
    @Autowired
    private JavaMailActive javaMailActive;

    /**
     * 注册
     * @return
     * @throws Exception
     */
    public String registerActive() throws Exception{
//     接收数据
//        System.out.println(repassword+"=============");
        String password = model.getPassword();
        String loginName = model.getLoginName();
        String gender = model.getGender();
        String email = model.getEmail();
//     密码要MD5加密
        System.out.println(password+"===============");
        password = DigestUtils.md5Hex(password);
//      向数据库插入数据
        model.setPassword(password);
        List<User> users =  this.userService.registerCheck(model);
        if(users.size()>0){
           ActionContext.getContext().put("message","用户已存在");
           return "registerFail";
        }
        this.userService.save(model);
        register = password+"_"+loginName+"_"+email;
        register = DigestUtils.md5Hex(register);
        users = this.userService.getByCondition(model);
        User user = users.get(0);
//        发送的信息包括register跟ID
        Long id = user.getId();
        register = id+"_"+register;
//        发送邮件
        javaMailActive.MailActive(register, email);
        return "registerActive";
    }

    public String androidRegister() throws Exception{
        return "";
    }
    /**
     * 激活
     * @return
     * @throws Exception
     */
    @SkipValidation
    public String registerConfirm() throws Exception{
        System.out.println("=============================================");
        String[] infos = register.split("_");
        for(String str:infos){
            System.out.println(str+"=======str========");
        }
        Long id = Long.parseLong(infos[0]);
        User user  = this.userService.getById(id);
        System.out.println(user+"========user========");
        if(user==null)
            return "error";
        String dbInfo = user.getPassword()+"_"+user.getLoginName()+"_"+user.getEmail();
        dbInfo = DigestUtils.md5Hex(dbInfo);
        System.out.println(dbInfo + "=============" + infos[1]);
//        若然是正确的激活邮件
        if(dbInfo.equals(infos[1])){
            user.setIsActive(true);
            this.userService.update(user);
            return "isActive";
        }
        return "error";
    }

    /**
     * loginInfo
     *登录
     * @return
     * @throws Exception
     */
    @SkipValidation
    public String Login() throws Exception{
        System.out.println(autoLogin+"=========autoLogin=========");
        String serviceCode =  (String)session.get("SESSION_SECURITY_CODE");
        System.out.println(serviceCode+"============="+securityCode);
        if(!serviceCode.equals(securityCode)){
            ActionContext.getContext().put("message","验证码错误");
            return "loginFail";
        }
        String password = DigestUtils.md5Hex(model.getPassword());
        model.setPassword(password);
        List<User> users = this.userService.getByCondition(model);
        System.out.println(model.toString()+"=============="+users.size());
        if(users==null|| users.size()<=0){
            ActionContext.getContext().put("message","不存在该用户或者密码错误");
            return "loginFail";
        }
        User user = users.get(0);
        if(user.getIsActive()){
            if(autoLogin!=null){
                System.out.println("======addCookie=====");
                HttpServletResponse response = ServletActionContext.getResponse();
                String loginInfo = user.getLoginName()+"_"+user.getPassword();
                CommomUtils.addCookie(loginInfo,"loginInfo",response);
            }
            System.out.println("======put session======");
            System.out.println(user.toString());
            this.session.put("user",user);
            return "loginSuccess";
        }
        ActionContext.getContext().put("message","用户没有激活");
        return  "loginFail";
    }

    /**
     * 注销
     * @return
     * @throws Exception
     */
    @SkipValidation
    public String loginOut() throws Exception{
//       从session里面删除
       this.session.remove("user");
//        从cookie里面删除
        HttpServletResponse response = ServletActionContext.getResponse();
        CommomUtils.delCookie(response,"loginInfo");
       return  "loginOut";
    }

    /**
     *
     * @return
     * @throws Exception
     */
    @SkipValidation
    public String checkInfo() throws Exception{
        System.out.println("==============checkInfo=============");
        List<User> users = this.userService.findAll();
        for (User user:users) {
            if (model.getEmail().trim()!= null && model.getEmail().equals(user.getEmail())) {
                this.emessage = "邮箱已经存在";
                return "checkInfo";
            }
            if (model.getLoginName().trim()!= null && model.getLoginName().equals(user.getLoginName())) {
                this.lmessage = "用户名已存在";
                return "checkInfo";
            }
        }
        return null;
      }
    public String getRegister() {
        return register;
    }

    public void setRegister(String register) {
        this.register = register;
    }

    public String getSecurityCode() {
        return securityCode;
    }

    public void setSecurityCode(String securityCode) {
        this.securityCode = securityCode;
    }

    public String getAutoLogin() {
        return autoLogin;
    }

    public void setAutoLogin(String autoLogin) {
        this.autoLogin = autoLogin;
    }

    public String getLmessage() {
        return lmessage;
    }

    public void setLmessage(String lmessage) {
        this.lmessage = lmessage;
    }

    public String getEmessage() {
        return emessage;
    }

    public void setEmessage(String emessage) {
        this.emessage = emessage;
    }


}
